//
//  SearchStarViewController.m
//  WULIHH
//
//  Created by tang on 16/4/14.
//  Copyright © 2016年 tang. All rights reserved.
//

#import "SearchStarViewController.h"
#import "Header.h"
#import "ContactModel.h"
#import "ContactDataHelper.h"

#import "WuLiHotSearchRequest.h"
#import "WuLiRequestFlowStar.h"
#import "WuLiRequestFlowStar.h"
#import "UserInfoModel.h"

#import "FirstSearchView.h"

#import "SearchStarViewCell.h"
@interface SearchStarViewController ()<UITableViewDataSource, UITableViewDelegate,SearchStarViewCellDelegate, FirstSearchViewDelegate>
{
    FirstSearchView *firstSearchView;
    
    UITableView *mainTableView;
    NSMutableArray *starInfoArray;
    
    NSArray *_sectionArr;//section arr
    NSMutableArray      *_rowArr;
    
    
    NSMutableArray *_searchResultArr;//搜索结果Arr
    
    BOOL        addUserStar;
}


@property (nonatomic,strong) NSMutableArray *dataArr;
//@property (nonatomic,strong) UIButton *searchDisplayController;

@end

@implementation SearchStarViewController



- (void)loadView
{
    [super loadView];

    _rowArr = [NSMutableArray new];
    //请求明星数据
    [WuLiHotSearchRequest requestStarList];
    
    starInfoArray = [NSMutableArray new];
    
    firstSearchView = [[FirstSearchView alloc] initWithFrame:CGRectMake(0, 0, WithView, 64.0)];
    [self.view addSubview:firstSearchView];

    
    mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, WithView, heightView-64.0) style:UITableViewStylePlain];
    [self.view addSubview:mainTableView];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _searchResultArr=[NSMutableArray array];
    
    [mainTableView setDataSource:self];
    [mainTableView setDelegate:self];
    [mainTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    [firstSearchView setMFirstSearchViewDelegate:self];
   
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getStarListBack:) name:getStarList object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addStarGetBack:) name:addStar object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tabBarController setHidesBottomBarWhenPushed:YES];
}




- (void)changeText:(NSString *)text
{
//    NSLog(@"%@", text);
    NSMutableArray *tempResults = [NSMutableArray array];
    NSUInteger searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
    
    for (int i = 0; i < self.dataArr.count; i++) {
        NSString *storeString = [(ContactModel *)self.dataArr[i] name];
        NSString *icon = [(ContactModel *)self.dataArr[i] iconUrl];
        
        NSNumber *numberid =[NSNumber numberWithInt:[(ContactModel *)self.dataArr[i] id]];
        NSNumber *numberflow =[NSNumber numberWithInt:[(ContactModel *)self.dataArr[i] isFollowed]];
        
        
        NSRange storeRange = NSMakeRange(0, storeString.length);
        
        NSRange foundRange = [storeString rangeOfString:text options:searchOptions range:storeRange];
        if (foundRange.length) {
            NSDictionary *dic=@{@"name":storeString,
                                @"iconUrl":icon,
                                @"id":numberid,
                                @"isFollowed":numberflow};
            
            [tempResults addObject:dic];
        }
        
    }
    [_searchResultArr removeAllObjects];
    [_searchResultArr addObjectsFromArray:tempResults];
    NSLog(@"%@", _searchResultArr);
    [mainTableView reloadData];
}





- (void)disMissSearch
{
    [self.navigationController popViewControllerAnimated:YES];
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_searchResultArr.count == 0)
    {
        return _rowArr.count;
    }
    else
    {
        return 1;
    }
    return 0;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    if (_searchResultArr.count == 0) {
        return [_rowArr[section] count];
    }else{
        
        return _searchResultArr.count;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 53.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //viewforHeader
    id label = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
    if (!label) {
        label = [[UILabel alloc] init];
        [label setFont:[UIFont systemFontOfSize:14.5f]];
        [label setTextColor:[UIColor grayColor]];
        [label setBackgroundColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1]];
    }
    [label setText:[NSString stringWithFormat:@"  %@",_sectionArr[section+1]]];
//    NSLog(@"%d", section);
    return label;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    return index-1;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 22.0;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellInden = @"cell";
    SearchStarViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellInden];
    if (!cell) {
        cell = [[SearchStarViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellInden];
    }
    
    if (_searchResultArr.count == 0)
    {
        [cell setMSearchStarViewCellDelegate:self];
        ContactModel *model=_rowArr[indexPath.section][indexPath.row];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell setModelwithName:model.name withImage:model.iconUrl buttonWithTag:indexPath.row withFlow:model.isFollowed withSectionInt:indexPath.section withStarID:model.id];

    }
    else
    {
        [cell setModelwithName:[_searchResultArr[indexPath.row] valueForKey:@"name"] withImage:[_searchResultArr[indexPath.row] valueForKey:@"iconUrl"] buttonWithTag:indexPath.row withFlow:[[_searchResultArr[indexPath.row] valueForKey:@"isFollowed"] intValue] withSectionInt:indexPath.section withStarID:[[_searchResultArr[indexPath.row] valueForKey:@"id"] intValue]];
    }
    

    return cell;
}


- (void)getStarListBack:(NSNotification *)notion
{
//    NSLog(@"%@", [notion object]);
    [starInfoArray removeAllObjects];
    
    if ([[notion object] intValue] == 1)
    {
        NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path=[paths objectAtIndex:0];
        NSString *Json_path=[path stringByAppendingPathComponent:@"starList.json"];
        //==Json数据
        NSData *data=[NSData dataWithContentsOfFile:Json_path];
         NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
//        NSLog(@"%@", dic);
        if ([[dic valueForKey:@"success"] intValue] == 1)
        {
            [starInfoArray addObjectsFromArray:[dic valueForKey:@"data"]];
            
            
            
            self.dataArr=[NSMutableArray array];
            for (NSDictionary *subDic in starInfoArray) {
                ContactModel *model=[[ContactModel alloc]initWithDic:subDic];
//                NSLog(@"%@", model);
                [self.dataArr addObject:model];
            }
            
            _rowArr=[ContactDataHelper getFriendListDataBy:self.dataArr];
//                NSLog(@"%@", _rowArr);
            
            _sectionArr=[ContactDataHelper getFriendListSectionBy:[_rowArr mutableCopy]];
            if (_searchResultArr.count == 0)
            {
                [mainTableView reloadData];
            }
            else
            {
                
            }
            


        }
        else
        {
            
        }
    }
    else
    {
        
    }
}



//添加关注
- (void)addStarGetBack:(NSNotification *)notion
{
//    NSLog(@"-----------%@", [notion userInfo]);
    NSDictionary *dic = [notion userInfo];
    if ([[dic valueForKey:@"success"] intValue] == 1)
    {
        if (addUserStar)        //添加明星
        {
            
        }
        else            //移除明星
        {
            
        }
//        [WuLiHotSearchRequest requestStarList];
        [WuLiRequestFlowStar requestFlowStarWithUserID:[UserInfoModel userIDString]];

    }
    else
    {
        
    }
}




//点击关注明星
- (void)pressGuanzhuWitghID:(NSString *)stringID withTag:(NSInteger)tag withSection:(NSInteger)section
{
    if ([yonghuDengluJudge isEqualToString:@"no"])
    {
        if (_searchResultArr.count == 0)
        {
            ContactModel *model=_rowArr[section][tag];
            model.isFollowed = 1;
            addUserStar = YES;
            
            [WuLiRequestFlowStar requestAddFlowStarWithUserID:stringID];
        }
        else
        {
            
        }
        
        NSIndexPath *te=[NSIndexPath indexPathForRow:tag inSection:section];
        [mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:te,nil] withRowAnimation:UITableViewRowAnimationFade];

    }
    else
    {
        
    }
    
}

//移除关注
- (void)pressDeleteGuanzhu:(NSString *)stringID withTag:(NSInteger)tag withSection:(NSInteger)section
{
    addUserStar = NO;
    if ([yonghuDengluJudge isEqualToString:@"no"])
    {
        if (_searchResultArr.count == 0)
        {
            ContactModel *model=_rowArr[section][tag];
            model.isFollowed = 0;
            [_rowArr[section] replaceObjectAtIndex:tag withObject:model];
            
            [WuLiRequestFlowStar requestDeletaFlowStarWithUserID:stringID];
        }
        else
        {
            
        }
        
        NSIndexPath *te=[NSIndexPath indexPathForRow:tag inSection:section];
        [mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:te,nil] withRowAnimation:UITableViewRowAnimationFade];

    }
    else
    {
        
    }
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
